﻿using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace DiagnosticsGeneratorMethod
{
    [Generator]
    public class DiagnosticsGenerator : ISourceGenerator
    {
        //声明的诊断，例如编译器错误或警告
        // 该实例中声明的是警告
        private static readonly DiagnosticDescriptor InvalidXmlWarning = new DiagnosticDescriptor(
                                        id: "XMLGEN001",
                                        title: "Couldn't parse XML file",
                                        messageFormat: "无法解析xml文件 '{0}'.",
                                        category: "DiagnosticsGenerator",
                                        DiagnosticSeverity.Warning,
                                        isEnabledByDefault: true);

        public void Execute(GeneratorExecutionContext context)
        {
            // 获得所有的xml文件（也可以是其他文件，都是要动态生成的并且有且只有一种标准）
            IEnumerable<AdditionalText> xmlFiles = context.AdditionalFiles.Where(at => at.Path.EndsWith(".xml", StringComparison.OrdinalIgnoreCase));
            foreach (AdditionalText xmlFile in xmlFiles)
            {
                XmlDocument xmlDoc = new XmlDocument();
                string text = xmlFile.GetText(context.CancellationToken).ToString();
                try
                {
                    // 该诊断的标准是所有xml文件都能转换为xml格式的文件
                    xmlDoc.LoadXml(text);
                }
                catch (XmlException)
                {
                    // 发现错误，并将诊断添加到编译器中
                    context.ReportDiagnostic(Diagnostic.Create(InvalidXmlWarning, Location.None, xmlFile.Path));
                    continue;
                }
            }
        }

        public void Initialize(GeneratorInitializationContext context)
        {
        }
    }
}


